package com.xin.beauty.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xin.beauty.listener.ItemExcelListener;
import com.xin.beauty.mapper.AdminMapper;
import com.xin.beauty.mapper.AdminRoleMapper;
import com.xin.beauty.mapper.RoleMapper;
import com.xin.beauty.pojo.entity.*;
import com.xin.beauty.mapper.ItemMapper;
import com.xin.beauty.pojo.query.ItemQuery;
import com.xin.beauty.pojo.vo.ItemExcelVO;
import com.xin.beauty.service.IAdminService;
import com.xin.beauty.service.IDoctorService;
import com.xin.beauty.service.IItemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xin.beauty.service.IProjectService;
import com.xin.beauty.util.ExcelUtil;
import com.xin.beauty.util.Result;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Xin
 * @since 2025-04-14
 */
@Service
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item> implements IItemService {
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    private IProjectService projectService;

    @Autowired
    private IDoctorService doctorService;

    @Autowired
    private IAdminService adminService;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Override
    public IPage<Item> list(ItemQuery itemQuery) {
        IPage<Item> page = new Page<>(itemQuery.getPage(), itemQuery.getLimit());
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(!ObjectUtils.isEmpty(itemQuery.getProjectName()), "project_name", itemQuery.getProjectName());
        queryWrapper.eq(!ObjectUtils.isEmpty(itemQuery.getDoctorId()), "doctor_id", itemQuery.getDoctorId());
        queryWrapper.eq(!ObjectUtils.isEmpty(itemQuery.getProjectId()), "project_id", itemQuery.getProjectId());
        AdminRole adminRole = adminRoleMapper.selectOne(new QueryWrapper<AdminRole>().eq("admin_id", itemQuery.getUserId()));
        Role role = roleMapper.selectOne(new QueryWrapper<Role>().eq("name", "用户"));
        if(adminRole.getRoleId().equals(role.getId())){
            queryWrapper.eq(!ObjectUtils.isEmpty(itemQuery.getUserId()), "user_id", itemQuery.getUserId());
        }
        Role roleDoctor = roleMapper.selectOne(new QueryWrapper<Role>().eq("name", "医美师"));
        if(adminRole.getRoleId().equals(roleDoctor.getId())){
            queryWrapper.eq(!ObjectUtils.isEmpty(itemQuery.getUserId()), "doctor_id", itemQuery.getUserId());
        }
        queryWrapper.between(!ObjectUtils.isEmpty(itemQuery.getBeginTime()) && !ObjectUtils.isEmpty(itemQuery.getEndTime()),
                "update_time", itemQuery.getBeginTime(), itemQuery.getEndTime());
        itemMapper.selectPage(page, queryWrapper);
        return page;
    }

    @Override
    public void exportExcel(HttpServletResponse response) {
        List<Item> list = itemMapper.selectList(null);
        ArrayList<ItemExcelVO> itemExcelVOList = new ArrayList<>();
        for (Item item : list) {
            ItemExcelVO itemExcelVO = new ItemExcelVO();
            BeanUtils.copyProperties(item, itemExcelVO);//new一个工具类 复制
            itemExcelVOList.add(itemExcelVO);//如果不做ItemExcelVO这些就不用做了 不想破坏item实体类
        }
        ExcelUtil.exportExcel(response, itemExcelVOList, ItemExcelVO.class, "item");
    }

    @Override
    public void importExcel(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), ItemExcelVO.class, new ItemExcelListener(itemMapper)).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Result add(Item item){
        if(ObjectUtils.isEmpty(item.getTime())){
            throw new RuntimeException("开始时间不能为空！");
        }
        if(ObjectUtils.isEmpty(item.getDoctorId())){
            throw new RuntimeException("医美师不能为空！");
        }
        if(ObjectUtils.isEmpty(item.getProjectId())){
            throw new RuntimeException("项目不能为空！");
        }
        Project project = projectService.getById(item.getProjectId());
        item.setProjectName(project.getName());
        Admin adminDoctor = adminService.getById(item.getDoctorId());
        item.setDoctorName(adminDoctor.getName());
        Admin admin = adminService.getById(item.getUserId());
        item.setUserName(admin.getName());
        item.setEndTime(addHour(item.getTime(),item.getLength()));
        List<Item> itemList = itemMapper.selectList(new QueryWrapper<Item>().eq("doctor_id", item.getDoctorId()));
        for(Item itemOne : itemList){
            if(!(item.getEndTime().before(itemOne.getTime()) || item.getTime().after(itemOne.getEndTime()))){
                throw new RuntimeException("美容师时间与您项目时间冲突，请重新选择！");
            }
        }
        List<Item> itemLists = itemMapper.selectList(new QueryWrapper<Item>().eq("user_id", item.getUserId()));
        for(Item itemOne : itemLists){
            if(!(item.getEndTime().before(itemOne.getTime()) || item.getTime().after(itemOne.getEndTime()))){
                throw new RuntimeException("您已预约的项目与当前项目有时间冲突，请重新选择！");
            }
        }
        itemMapper.insert(item);
        return null;
    }

    public static Date addHour(Date date,int i){
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.HOUR_OF_DAY, i);
        Date newDate = c.getTime();
        return newDate;
    }

    @Override
    public Result updateItem(Item item) {
        if(ObjectUtils.isEmpty(item.getTime())){
            throw new RuntimeException("开始时间不能为空！");
        }
        if(ObjectUtils.isEmpty(item.getDoctorId())){
            throw new RuntimeException("医美师不能为空！");
        }
        if(ObjectUtils.isEmpty(item.getProjectId())){
            throw new RuntimeException("项目不能为空！");
        }
        Project project = projectService.getById(item.getProjectId());
        item.setProjectName(project.getName());
        Admin adminDoctor = adminService.getById(item.getDoctorId());
        item.setDoctorName(adminDoctor.getName());
        Admin admin = adminService.getById(item.getUserId());
        item.setUserName(admin.getName());
        item.setEndTime(addHour(item.getTime(),item.getLength()));
        List<Item> itemList = itemMapper.selectList(new QueryWrapper<Item>().eq("doctor_id", item.getDoctorId()));
        for(Item itemOne : itemList){
            if(!itemOne.getId().equals(item.getId())){
                if(!(item.getEndTime().before(itemOne.getTime()) || item.getTime().after(itemOne.getEndTime()))){
                    throw new RuntimeException("美容师时间与您项目时间冲突，请重新选择！");
                }
            }
        }
        List<Item> itemLists = itemMapper.selectList(new QueryWrapper<Item>().eq("user_id", item.getUserId()));
        for(Item itemOne : itemLists){
            if(!itemOne.getId().equals(item.getId())) {
                if (!(item.getEndTime().before(itemOne.getTime()) || item.getTime().after(itemOne.getEndTime()))) {
                    throw new RuntimeException("您已预约的项目与当前项目有时间冲突，请重新选择！");
                }
            }
        }
        itemMapper.updateById(item);
        return null;
    }

}
